package com.hafu.dao;

import com.hafu.model.KuCun;
import com.hafu.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class KuCunDao {
    ArrayList<KuCun> list = new ArrayList<>();
    public ArrayList<KuCun> getKuCunList()
    {
        //获取连接
        Connection  conn= DbUtil.getConn();
        //获取sql
        String sql="select * from kucun";
        try {
            PreparedStatement preparedStatement= conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                int id=resultSet.getInt("id");
                String spname=resultSet.getString("spname");
                int num=resultSet.getInt("num");
                KuCun kuCun1=new KuCun(id,spname,num);
                list.add(kuCun1);
            }

        } catch (SQLException  throwables) {
            throwables.printStackTrace();
        }
        return list;
    }
    public KuCun getKuCunBySpName(String spName,Connection conn) throws SQLException{
        String sql="select * from kucun where spname=?";
        PreparedStatement preparedStatement=conn.prepareStatement(sql);
        preparedStatement.setString(1,spName);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()){
            int id=resultSet.getInt("id");
            int num=resultSet.getInt("num");
            String name=resultSet.getString("spname");
            KuCun kuCun=new KuCun(id,spName,num);
            return kuCun;
        }
        return null;
    }
    public boolean updateKuCun(KuCun kuCun,Connection conn) throws SQLException{
        String sql="update kucun set num=? where spname=?";
        PreparedStatement preparedStatement=conn.prepareStatement(sql);
        preparedStatement.setInt(1,kuCun.getNum());
        preparedStatement.setString(2,kuCun.getSpname());
        int i=preparedStatement.executeUpdate();
        if (i>0) {
            return true;
        }else return false;
    }
    public boolean addKuCun(KuCun kuCun,Connection conn) throws SQLException{
        String sql="insert into kucun(spname,num) values(?,?)";
        PreparedStatement preparedStatement=conn.prepareStatement(sql);
        preparedStatement.setString(1,kuCun.getSpname());
        preparedStatement.setInt(2,kuCun.getNum());
        int i=preparedStatement.executeUpdate();
        if (i>0) {
            return true;
        }else return false;
    }
}
